import axios from 'axios'
import {BASE_URL} from '@/config/api'
import router from '@/routes/index'
import {message} from 'element-ui'
import * as tokenTools from '@/utils/tokenTools.js'
import {getToken} from '@/utils/tokenTools.js'
import qs from 'qs'

const service = axios.create({
    baseURL: process.env.NODE_ENV === 'production' ? BASE_URL : '/api/',
    timeout: 60000, // 请求超时uploadBuildExcel
    responseType: 'json',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'token': getToken()
    },
})

service.interceptors.request.use(config => {
    if (!config.headers.token && tokenTools.getToken()) {
        config.headers.token = tokenTools.getToken()
    }
    return config
})

let reflashFlag = false
// let lastCode = ''
service.interceptors.response.use(res => res, err => {
    if (!reflashFlag) {
        if ([401, 402, 403].includes(Number(err.response.status))) {
            reflashFlag = true
            service({
                url: 'login/referToken',
                method: 'post',
                data: qs.stringify({
                    'refer_token': tokenTools.getReferToken()
                }),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                },
            })
                .then(res => {
                    if (res.data.code === 1) {
                        tokenTools.setToken(res.data.data.token)
                        tokenTools.setReferToken(res.data.data.refer_token)
                        // router.push({path: '/listhome'})
                        setTimeout(() => {
                            location.reload()
                        }, 500)
                    } else {
                        reflashFlag = false
                        // if (lastCode !== '4xx') {
                        //     lastCode = '4xx'
                        message({
                            type: 'warning',
                            message: 'please login'
                        })
                        // }
                        tokenTools.setToken('')
                        router.push({name: 'listlogin'})
                    }
                })
        }
    }
})

export default service
